package com.chen.bpsptsystem.service;

import com.chen.bpsptsystem.common.ServerResponse;
import com.chen.bpsptsystem.dao.ClazzMapper;
import com.chen.bpsptsystem.dao.MaterialMapper;
import com.chen.bpsptsystem.po.Clazz;
import com.chen.bpsptsystem.po.ClazzExample;
import com.chen.bpsptsystem.po.Material;
import com.chen.bpsptsystem.po.MaterialExample;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @author chen
 */
@Service
public class IClazzService {

    @Resource
    private ClazzMapper clazzMapper;
    @Resource
    private MaterialMapper materialMapper;

    public ServerResponse add(Clazz interest) {
        ClazzExample example = new ClazzExample();
        ClazzExample.Criteria criteria = example.createCriteria();
        criteria.andNameEqualTo(interest.getName());
        List<Clazz> list = clazzMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(list)) {
            return ServerResponse.createByErrorMsg("已存在");
        }
        int i = clazzMapper.insertSelective(interest);
        if (i > 0) {
            return ServerResponse.createBySuccess(interest);
        }
        return ServerResponse.createByErrorMsg("新增失败");
    }


    public ServerResponse list(Integer pn, Integer pageSize, String name) {
        PageHelper.startPage(pn, pageSize);
        ClazzExample example = new ClazzExample();
        ClazzExample.Criteria criteria = example.createCriteria();
        criteria.andNameLike(name);
        List<Clazz> clazzes = clazzMapper.selectByExample(example);
        PageInfo<Clazz> info = new PageInfo<>(clazzes);
        return ServerResponse.createBySuccess(info);
    }

    public ServerResponse delete(Integer id) {
        int row = clazzMapper.deleteByPrimaryKey(id);
        if (row > 0) {
            return ServerResponse.createBySuccessMsg("删除成功");
        }
        return ServerResponse.createByErrorMsg("删除失败");
    }

    public ServerResponse edit(Clazz interest) {
        int row = clazzMapper.updateByPrimaryKeySelective(interest);
        if (row > 0) {
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByErrorMsg("修改失败");
    }

    public ServerResponse clazzDetail(Integer id) {

        //班级的属性和班级的资料
        Map<String,Object> clazz = clazzMapper.findById(id);
        MaterialExample example = new MaterialExample();
        MaterialExample.Criteria criteria = example.createCriteria();
        criteria.andClazzIdEqualTo(String.valueOf(id));
        List<Material> materials = materialMapper.selectByExample(example);
        clazz.put("materials",materials);
        return ServerResponse.createBySuccess(clazz);
    }
}
